<template>
  <view class="container">
    <custom-nav></custom-nav>
    <view class="content">
      <view class="con-card" v-for="(item, index) in infoConf" :key="index">
        <view class="con-title">{{item.title}}
          <view class="l-text" @click="toSmallText" v-if="item.type == 'smalltext'">
            <view class="l-e-text" v-if="!completeForm.smalltext">请填写</view>
            <view style="width:40rpx;height:40rpx;margin-left:10rpx">
              <image src="@/subPages/static/arrow-right.svg" mode="scaleToFill" style="width: 40rpx; height: 40rpx" />
            </view>
          </view>
        </view>
        <view class="con-tips">{{item.tips}}</view>

        <!-- 照片 -->
        <template v-if="item.type == 'picture'">
          <view style="padding: 30rpx 0 20rpx">
            <custom-picture :imgList="imgList"></custom-picture>
          </view>
        </template>

        <!-- 相亲说明 -->
        <template v-else-if="item.type == 'smalltext'">
          <view class="com-desc" style="color:#333" @click="toSmallText" v-if="completeForm.smalltext">{{completeForm.smalltext}}</view>
          <view class="com-desc" @click="toSmallText" v-else>{{item.content}}</view>
        </template>

        <!-- 其他 -->
        <template v-else>
          <view v-for="(v, i) in item.options" :key="i" class="con-item">
            <list-card :item="v" :dataForm="completeForm" @openPopup="openPopup"></list-card>
          </view>
        </template>
      </view>
    </view>

    <view class="com-bottom">
      <view class="c-btn" @click="submitFn"> <custom-btn>完成</custom-btn> </view>
    </view>

    <!-- 年龄、身高、家乡弹窗 -->
    <uni-popup ref="popupRef" type="bottom" @maskClick="close" :mask-click="false" :safe-area="false" mask-background-color="rgba(0,0,0,0.7)">
      <view class="popup-con">
        <image :src="closeIcon" mode="widthFix" class="popup-close" @click="close" />
        <template>
          <view class="popup-title">{{pageConf.title}}</view>
          <template v-if="popupType == 'button'">
            <button-card :mode="popupMode" :formData="completeForm" :range="pageConf.range"></button-card>
          </template>

          <template v-else-if="popupType == 'single'">
            <view class="popup-text">{{completeForm[popupMode]}}</view>
            <picker-item :mode="popupMode" :formData="completeForm" :range="pageConf.range"></picker-item>
          </template>

          <template v-else-if="popupType == 'custom'">
            <view class="popup-text">{{mateForm[pickerMode]}}</view>
            <custom-picker :mode="pickerMode" :modelData="mateForm"></custom-picker>
          </template>

          <view class="s-btn" @click="surePopup" v-if="!isSingle"><custom-btn>完成</custom-btn></view>
        </template>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import ListCard from "./components/list-card.vue";
import ButtonCard from "./components/button-card.vue";
import PickerItem from "@/components/picker/picker-item.vue";
import closeIcon from "@/static/common/close.svg";

// 引入api
import { infoConfig } from "./config";
import { pageConfig } from "./config/create";
import { setItem, getItem } from "@/utils/storage";
import { editUserDetail } from "@/api/my";
import useStore from "@/store";
const { app, common, register } = useStore();

const popupRef = ref();
const infoConf = reactive(infoConfig());
const popupType = ref("");
const popupMode = ref("");
const pickerMode = ref("");
const imgList = ref([]);
const isLoading = ref(false);
const completeForm = reactive({
  relation: "",
  height: "",
  edu: "",
  mate_address: "",
  income: "",
  marriage: "",
  house: "",
  car: "",
  num: "",
  region: "", // 家乡, 用于页面渲染
  mate_edu_val: "", // 择偶学历, 用于数据传递
});

const mateForm = reactive({
  age: "",
  height: "",
  region: "", // 家乡, 用于数据传递
});

const isSingle = computed(() => ["marriage", "house", "car", "day_marr"].includes(popupMode.value));

// popup字段配置
const registerConf = computed(() => register.registerConf);
const pageConf = computed(() => {
  const t = popupMode.value;
  const conf = pageConfig(t) || { range: [] };
  conf.range = registerConf.value[t] || conf.range;

  if (t == "height") {
    const list = Object.values(conf.range);
    const resList = list.reduce((a, b) => a.concat(b), []);
    conf.range = resList;
  }

  if (t == "mate_edu_val") {
    conf.range = registerConf.value["mate_edu"] || conf.range;
  }

  return conf;
});

// 单项picker
const fetchPopupType = (t) => {
  const tArr = [
    {
      key: "button",
      options: ["relation", "marriage", "house", "car", "day_marr"],
    },
    {
      key: "single",
      options: ["height", "edu", "income", "mate_edu_val"],
    },
    {
      key: "custom",
      options: ["mate_height", "mate_age", "region"],
    },
  ];
  let type = "";
  tArr.forEach((v) => {
    if (v.options.includes(t)) {
      type = v.key;
      return;
    }
  });

  popupType.value = type;
};

// 调起popup
const openPopup = (t) => {
  // 性别 + 年龄 + 现居地  -- 联系客服修改
  const ks = ["gender", "full_year", "at_city", "num"];
  if (ks.includes(t)) {
    common.updatePopupOpen(true, "serve");
    return;
  }
  // 其他操作
  popupMode.value = t;

  if (t == "mate_age") pickerMode.value = "age";
  if (t == "mate_height") pickerMode.value = "height";
  if (t == "region") pickerMode.value = "region";

  if (t == "mate_edu") popupMode.value = "mate_edu_val";

  fetchPopupType(popupMode.value);

  nextTick(() => {
    if (registerConf.value?.year) {
      popupRef.value.open();
    }
  });
};

// 检查数值是否符合正确逻辑
const isCheckNum = (m) => {
  let flag = true;
  if (mateForm[m] != "不限") {
    const params = mateForm[m].split("到");

    const min = params[0].match(/^\d+/);
    const max = params[1].match(/^\d+/);

    const tObj = {
      age: "年龄",
      height: "身高",
    };
    if (min || max) {
      if (Number(min) > Number(max)) {
        uni.showToast({
          title: tObj[m] + "选择区间格式不正确",
          icon: "none",
        });
        flag = false;
        return;
      }
      if (Number(max) < Number(min)) {
        uni.showToast({
          title: tObj[m] + "选择区间格式不正确",
          icon: "none",
        });
        flag = false;
        return;
      }
    }
  }

  return flag;
};

const surePopup = () => {
  if (popupMode.value == "mate_age") {
    if (!isCheckNum("age")) return;
  }
  if (popupMode.value == "mate_height") {
    if (!isCheckNum("height")) return;
  }

  const keys = ["mate_age", "mate_height", "region"];
  if (keys.includes(popupMode.value)) {
    keys.forEach((v) => {
      const k = v.split("mate_")[1];
      if (k) completeForm[v] = mateForm[k];
      if (v == "region") {
        const [p, c] = mateForm.region.split(",");
        completeForm[v] = `${p}${c}`;
      }
    });
  }

  updateUserInfo("popup");
};

// 跳转相亲说明
const toSmallText = () => {
  setItem("editUser", { smalltext: completeForm.smalltext });
  uni.navigateTo({ url: "/subPages/complete/other?type=smalltext" });
};

// 提交
const submitFn = () => {
  uni.navigateBack({ delta: 1 });
};

const close = () => {
  if (popupMode.value == "mate_age") {
    if (!isCheckNum("age")) return;
  }
  if (popupMode.value == "mate_height") {
    if (!isCheckNum("height")) return;
  }
  popupMode.value = "";
  popupType.value = "";
  popupRef.value.close();
};

const getImgs = (imgs) => {
  const list = [
    {
      picObj: {},
      tips: "孩子正面照",
      icon: "upload",
    },
    {
      picObj: {},
    },
    {
      picObj: {},
    },
  ];
  if (imgs?.length) {
    list.forEach((item, index) => {
      if (imgs[index]) {
        item.picObj = imgs[index];
      } else {
        item.picObj = {};
      }
    });
  }
  imgList.value = list;
};

// 获取信息
const getInfo = () => {
  isLoading.value = true;
  const res = getItem("user_info");
  for (const key in res) {
    completeForm[key] = res[key];
  }
  let { imgs, at_province, at_city, old_province, old_city, mate_address } = res;
  getImgs(imgs);

  // 家乡
  if (old_province || old_city) {
    completeForm.region = `${old_province}${old_city}`;
    mateForm.region = `${old_province},${old_city}`;
  }
  if (old_city && !old_province) {
    mateForm.region = `${old_city},${old_city}`;
  }

  // 择偶地区
  if (mate_address) {
    const res_address = JSON.parse(mate_address);
    const new_address = res_address.filter((v) => v.city);
    completeForm.mate_address = new_address;
    const lastAddress = new_address.map((v) => v.city);
    completeForm.mate_region = lastAddress.join(",");
  } else {
    completeForm.mate_address = [{ province: at_province, city: at_city }];
    completeForm.mate_region = at_city;
  }

  // 择偶年龄+身高+学历
  mateForm.age = res.mate_age;
  mateForm.height = res.mate_height;
  completeForm.mate_edu_val = res.mate_edu;
  isLoading.value = false;
};

// 更新保存信息
const updateUserInfo = (type, prop) => {
  const t = prop || popupMode.value;

  const newForm = JSON.parse(JSON.stringify(completeForm));

  let user_info = {
    [t]: newForm[t],
  };
  // 家乡
  if (t == "region") {
    user_info = {};
    const { region } = mateForm;
    const [old_province, old_city] = region?.split(",") || [];
    user_info.old_province = old_province;
    user_info.old_city = old_city;
    if (old_province == old_city) {
      user_info.old_province = "";
      completeForm.region = old_city;
    }
  }

  // 择偶学历
  if (t == "mate_edu_val") {
    user_info.mate_edu = user_info.mate_edu_val;
    completeForm.mate_edu = user_info.mate_edu;
    delete user_info.mate_edu_val;
  }

  const params = {
    user_info: JSON.stringify(user_info),
  };

  editUserDetail(params)
    .then((res) => {
      if (type == "popup") {
        close();
      }
    })
    .catch((err) => {
      uni.showToast({
        title: err,
        icon: "none",
      });
    });
};

onShow(() => {
  const data = getItem("editUser");
  if (data) {
    for (const key in data) {
      completeForm[key] = data[key];
      if (key == "mate_address") {
        const res_address = data[key]?.map((v) => v.city);
        completeForm.mate_region = res_address.join(",");
      }
    }
    if (data.mobile) completeForm.phone = data.phone;
  }
});

onLoad(() => {
  register.getAttrConfig();
  getInfo();
});

onUnload(() => {
  uni.removeStorageSync("editUser");
});

provide("updateUserInfo", updateUserInfo);
</script>

<style lang=scss scoped>
@import "@/styles/global.scss";
.con-card {
  padding: 40rpx 30rpx 0;
  margin: 20rpx 0;
  background: #fff;
  .con-title {
    font-weight: 800;
    font-size: 44rpx;
    color: #000;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .con-tips {
    font-weight: 400;
    font-size: 28rpx;
    color: #888;
  }
  .con-item + .con-item {
    border-top: 1rpx solid #ededed;
  }
}

.com-bottom {
  border-top: 1px solid #ededed;
  padding: 40rpx 60rpx 120rpx;
  background: #ffffff;
  .c-btn {
    width: 100%;
    height: 120rpx;
    line-height: 120rpx;
    font-weight: 600;
    font-size: 40rpx;
    color: #fff;
    background: #ff5c55;
    border-radius: 120rpx;
  }
}

.com-desc {
  padding: 20rpx 0 30rpx;
  font-weight: 500;
  font-size: 32rpx;
  color: #aaa;
  line-height: 50rpx;
}

.popup-con {
  border-radius: 40rpx 40rpx 0 0;
  background: #fff;
  padding: 60rpx 70rpx;
  text-align: center;
  position: relative;
  .popup-title {
    font-size: 48rpx;
    color: #000;
    font-weight: 800;
    padding-bottom: 20rpx;
  }
  .popup-text {
    font-weight: bold;
    font-size: 32rpx;
    color: #f65952;
  }
}

.s-btn {
  width: 490rpx;
  height: 120rpx;
  line-height: 120rpx;
  background: #f65952;
  border-radius: 120rpx;
  font-weight: 800;
  font-size: 36rpx;
  color: #fff;
  margin: 60rpx auto;
}
.popup-close {
  position: absolute;
  width: 60rpx;
  height: 60rpx;
  right: 40rpx;
  top: 40rpx;
  z-index: 999;
}

.l-text {
  display: flex;
  align-items: center;
  font-weight: bold;
  font-size: 32rpx;
  color: #000;
  .l-e-text {
    color: #ff5c55;
  }
}
</style> 